from fastapi import HTTPException
from sqlalchemy.orm import Session, joinedload

from models import *


def get_message(message_id: str) -> Message:
    with Session(engine) as session:
        message = (
            session.query(Message).options(joinedload(Message.analysis)).get(message_id)
        )
        if not message:
            raise HTTPException(status_code=404, detail="Message不存在，请检查ID。")
    return message


def get_analysis(message_id: str) -> MessageAnalysis:
    with Session(engine) as session:
        analysis = (
            session.query(MessageAnalysis)
            .options(joinedload(MessageAnalysis.message))
            .filter(MessageAnalysis.message_id == message_id)
            .first()
        )
        if not analysis:
            raise HTTPException(status_code=404, detail="Message分析不存在，请检查ID。")
        return analysis


def get_chat(chat_id: str) -> Chat:
    with Session(engine) as session:
        chat = session.query(Chat).options(joinedload(Chat.analysis)).get(chat_id)
        if not chat:
            raise HTTPException(status_code=404, detail="Chat不存在，请检查ID。")
    return chat


def get_summary(chat_id: str) -> ChatAnalysis:
    with Session(engine) as session:
        summary = (
            session.query(ChatAnalysis)
            .options(joinedload(ChatAnalysis.chat))
            .filter(ChatAnalysis.chat_id == chat_id)
            .first()
        )
        if not summary:
            raise HTTPException(status_code=404, detail="Chat总结不存在，请检查ID。")
        return summary
